package com.jet.chat.thread;

import com.jet.chat.exception.ChatException;
import com.jet.chat.exception.ChatExceptionMessageRead;
import com.jet.chat.message.Message;
import com.jet.chat.message.MessageReader;
import com.jet.chat.message.MessageWriter;

public abstract class ChatAbstractThread implements Runnable {
	private MessageReader reader;
	private MessageWriter writer;
	private String exitReason;
	
	public ChatAbstractThread(MessageReader reader, MessageWriter writer, String exitReason) {
		this.reader = reader;
		this.writer = writer;
		this.exitReason = exitReason;
	}

	@Override
	public void run() {
		Message chatMessage;
		try {
			while (((chatMessage = reader.read()) != null) && (chatMessage.getContent() != null)) {
				//System.out.println("after read: " + chatMessage.getContent());
				sendMessageIfMessageIsNotSlashQ(chatMessage);
			}
			System.out.println(exitReason);
			System.exit(0);
		} catch (ChatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(exitReason);
		System.exit(0);
		//postmain();
	}
	
	public void sendMessageIfMessageIsNotSlashQ(Message chatMessage) throws ChatException {
		if (chatMessage.getContent().equals("/q")) {
			System.out.println(exitReason);
			System.exit(0);
		} else if (chatMessage.getContent().equals("")) {
		} else {
			writer.write(chatMessage);
		}
	}
	
	public void crash(ChatExceptionMessageRead e) {
		e.printStackTrace();
	}
	
	//public abstract void postmain();

}
